import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;


public class GameFinder {
	private static ArrayList<Game> availableGames;
	private static Socket s;
	public static ArrayList<Game> findGames(){
		availableGames = new ArrayList<Game>();
		String[] ipsInLab = {"gandalf","shadowfax","gimli","legolas","boromir","aragon","pippin","merry","sam","frodo"};
		for (String ip: ipsInLab){
			try {
				s = new Socket(ip, 8888);
				//Scanner in = new Scanner(System.in);
				PrintWriter writer = new PrintWriter(s.getOutputStream());
				System.out.println("Connection to " + "192.168.0.1" + " is open");
				StringBuilder msg = new StringBuilder();
				//System.out.println("Begin message; type ! by itself when done");
				msg.append("host_request\n");
				
				writer.print(msg.toString());
				writer.flush();
				BufferedReader responses = 
						new BufferedReader
						(new InputStreamReader(s.getInputStream()));
				int counter = 0;
				while (!responses.ready()){Thread.sleep(50); counter++;}
				System.out.println("Counter:"+counter);
				if (responses.ready()){
					String response = responses.readLine();
					if (response.length() >= 4&&response.substring(0,4).equals("True")){
						System.out.println(response);
						String details = response.substring(5);
						
						Game game = new Game(ip,details);
						System.out.println("Game found @ "+ ip);
						availableGames.add(game);
					}
				}
				else{
					System.out.print("No game available @ "+ip);
				}
			} catch (IOException ioe) {
				System.out.println("No game available @ "+ip);
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (s != null) {s.close();}
				} catch (IOException ioe) {
					System.out.println("error closing socket");
				}
			}

		}
		return availableGames;
	}
	public static void main(String[] args){
		final TexasReceiver receiver;
		try {
			receiver = new TexasReceiver(8888);
			receiver.setNotificationListener(new NotificationCenter(){

				@Override
				public void playerMadeMove(Turn t) {
					System.out.println(t);

				}

				@Override
				public void cardsReceived(HandCards h) {
					System.out.println(h);

				}

			});

			Thread server = new Thread(){
				@Override
				public void run(){
					try {

						receiver.setDeviceAsHost(true, "Connor's Table");
						receiver.listen();
					} catch (IOException e) {
						System.out.println("Socket closed");
					}
				}
			};
			server.start();
			Thread.sleep(50);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		findGames();
		
	}
}
